package com.midea.freecolder;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author wangwl23
 * 反射机制的学习
 * */
public class TestReflect {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Person person = new Person();
        person.age = 22;
        test(person);

    }
    public static void test (Object object) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class clazz = object.getClass();
        Field field = clazz.getDeclaredField("age");
        System.out.println(field.getInt(object));
        Method method = clazz.getDeclaredMethod("sayHello");
        //假如sayHello方法是私有的，设置可访问
        method.setAccessible(true);
        method.invoke(object);
        //运行时是否有MyAnno注解
        System.out.println(clazz.isAnnotationPresent(MyAnno.class));

        //打印出filed字段上的注解--bb
        System.out.println(field.getDeclaredAnnotation(MyAnno.class).name());
    }
}

@MyAnno
class Person{
    @MyAnno(name = "bb")
    int age;
    @MyAnno
    private void sayHello(){
        System.out.println("hello");
    }
}
